<?php

class Application_Model_Users
{

	protected $_dbTable;

	public function listAll()
	{
		$res = $this->getDbTable()->fetchAll()->toArray();
		if (count($res) == 0) {
			return;
		}
		$users = array();
		foreach ($res as $r) {
			$users[] = $this->constrUser($r);
		}
		return $users;
	}
	
	public function findById($id){
		$id = (int) $id;
		$result = $this->getDbTable()->find($id);
		if (count($result) == 0) {
			return;
		}
		$row = $result->current();
		$user = $this->constrUser($row);
		return $user;
	}

	public function save(Application_Model_User $user)
	{
		$newUser = array(
			'id' => $user->getId(),
			'fname' => $user->getFname(),
			'lname' => $user->getLname()
		);
		foreach ($user->getVarList() as $var) {
			$newUser[$var] = $user->get($var);
		}
		Zend_Debug::dump($newUser);
		if (isset($newUser['id']) || $newUser['id'] != null) {
			$this->getDbTable()->update($newUser, array('id = ?' => $user->getId()));
		} else {
			$this->getDbTable()->insert($newUser);
		}
	}

	public function constrUser($rUser)
	{
		$user = new Application_Model_User;
		$user->setFname($rUser['fname'])
				->setLname($rUser['lname']);
		if(isset($rUser['id'])){
			$user->setId($rUser['id']);
		}
		foreach ($rUser as $k => $v) {
			if ($k == 'id' || $k == 'fname' || $k == 'lname')
				continue;
			$user->set($k, $v);
		}
		return $user;
	}

	protected function getDbTable()
	{
		if ($this->_dbTable === null) {
			$this->setDbTable('Application_Model_DbTable_Users');
		}
		return $this->_dbTable;
	}

	protected function setDbTable($dbTable)
	{
		$db = new $dbTable();
		if (!$db instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $db;
		return $this;
	}

}

